#include<stdio.h> 
#include<stdlib.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<string.h>
#include"io.h"
#include<unistd.h>
static myfile* buyfile(int fd,int flag)
{
    myfile* file=(myfile*)malloc(sizeof(myfile));
    if(file==NULL) return NULL;
    file->bufferlen=0;
    file->fileno=fd;
    file->flag=flag;
    file->flush_method=line_flush;
    memset(file->outbuffer,0,sizeof(file->outbuffer));
    return file;
}
myfile* myfopen(const char* path,const char* mode)
{
    int fd=-1;
    int flag=0;
    if(strcmp(mode,"w")==0) {
        flag=O_CREAT|O_WRONLY|O_TRUNC;
        fd=open(path,flag,0666);
    }
    else if(strcmp(mode,"a")==0) {
        flag=O_CREAT|O_APPEND|O_WRONLY;
        fd=open(path,flag,0666);
    }
    else if(strcmp(mode,"r")==0) {
        flag=O_RDONLY;
        fd=open(path,flag);
    }
    if(fd<0) return NULL;
    return buyfile(fd,flag);
}
void myfclose(myfile* file)
{
    if(file->fileno<0) return;
    myfflush(file);
    close(file->fileno);
    free(file);
}
int myfwrite(myfile* file,const void* str,int len)
{
    memcpy(file->outbuffer+file->bufferlen,str,len);//向语言层缓冲区写入
    file->bufferlen+=len;
    //尝试判断刷新条件
    if(file->flush_method&line_flush&&file->outbuffer[file->bufferlen-1]=='\n')
        myfflush(file);
    return 0;
}
void myfflush(myfile* file)
{
    if(file->bufferlen<=0||file->fileno<0) return;
    write(file->fileno,file->outbuffer,file->bufferlen);
    file->bufferlen=0;
}
